import { isAbsoluteUrl, absoluteGo } from '@/utils/path';

export default {
  methods: {
    updateRouteQuery(query, { replace = false } = {}) {
      const oldQuery = this.$router.history.current.query;
      const path = this.$router.history.current.path;
      // 对象的拷贝
      const newQuery = JSON.parse(JSON.stringify(oldQuery));
      if (replace) {
        return this.$router.replace({ path, query: { ...newQuery, ...query } });
      } else {
        return this.$router.push({ path, query: { ...newQuery, ...query } });
      }
    },
    getHref(href) {
      if (href) {
        return isAbsoluteUrl(href) ? href : this.$router.resolve(href).href;
      } else {
        return 'javascript:;';
      }
    },
    /**
     * URL跳转
     * @param {Rawlocation} url 目标URL
     * @param {boolean} replace 是否使用replace方式跳转
     */
    goTo(url, replace = false) {
      if (!url) {
        throw new Error('invalid url');
      }

      const isStringUrl = typeof url === 'string';
      if (isStringUrl) {
        // prevent goTo('javascript?')
        if (/^javas/.test(url)) {
          return;
        }
        if (url === 'BACK') {
          this.$router.go(-1);
          return;
        }
        if (isAbsoluteUrl(url)) {
          return absoluteGo(url, replace);
        }
      }

      this.$router[replace ? 'replace' : 'push'](url);
    },
  },
};
